package bishi;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

// CompletableFuture的使用
public class demo4 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 使用默认的 ForkJoinPool 异步执行一个 Supplier
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return 42;
        });

        System.out.println("主线程可以继续做其他事情...");
        Integer result = future.get();
        System.out.println("计算结果是: " + result);

        CompletableFuture.supplyAsync(()->{
            System.out.println("任务1开始：" + Thread.currentThread().getName());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello";
        }).thenApply(s1 -> {
            System.out.println("任务2开始：" + Thread.currentThread().getName());
            return s1 + " World";
        }).thenAccept(s2 -> {
            System.out.println("最终结果是：" + s2);
        }).join();

        System.out.println("主线程结束");


        // 模拟获取用户ID
        CompletableFuture<String> getUser = CompletableFuture.supplyAsync(() -> "user123");

        // 模拟获取用户偏好
        CompletableFuture<String> getPreference = CompletableFuture.supplyAsync(() -> "Preference_A");

        // 将两个独立任务的结果合并
        CompletableFuture<String> combinedFuture = getUser.thenCombine(getPreference, (userId, preference) -> {
            return "为用户 " + userId + " 推荐 " + preference + " 类商品";
        });

        // 获取合并后的结果
        System.out.println(combinedFuture.join());

        CompletableFuture.supplyAsync(() -> {
                    if (true) { // 模拟一个错误
                        throw new RuntimeException("Oops! Something went wrong!");
                    }
                    return "Success";
                })
                .exceptionally(ex -> { // 异常处理，返回一个默认值
                    System.out.println("发生异常: " + ex.getMessage());
                    return "Default Value";
                })
                .thenAccept(result1 -> System.out.println("结果是: " + result1))
                .join();
    }
}
